package controller;

import java.sql.SQLException;
import java.util.ArrayList;

import model.Country;

import db.DBConnection;
import db.DBCountry;
import db.IFCountry;

public class CountryController {

	private static CountryController instance = null;

	public static CountryController getInstance()
		{
			if(instance == null)
				instance = new CountryController();

			return instance;
		}	
	public CountryController()
		{

		}	
	public Country getOneCountry(String clause, String search) throws SQLException
		{
			IFCountry dbCountry = new DBCountry();
			Country country = new Country();
			country = dbCountry.getOne(clause, search);
			return country;
		}
	public ArrayList<Country> findCountriesByAllInfo(String search) throws SQLException
	{
		IFCountry dbCountry = new DBCountry();
		ArrayList<Country> allCountries = new ArrayList<Country>();
		allCountries = dbCountry.getCountriesByAllInfo(search);
		return allCountries;
	}
	public ArrayList<Country> getAllCountries() throws SQLException
	{
		IFCountry dbCountry = new DBCountry();
		ArrayList<Country> allCountries = new ArrayList<Country>();
		allCountries = dbCountry.getAllCountries();
		return allCountries;
	}
	public ArrayList<Country> findByName(String name) throws SQLException
	{
		IFCountry dbCountry = new DBCountry();
		return dbCountry.getCountryByName(name);
	}
	public ArrayList<Country> findByTld(String tld) throws SQLException
	{
		IFCountry dbCountry = new DBCountry();
		return dbCountry.getCountryByTld(tld);
	}
	public int updateCountry(int id, String name, String tld) throws SQLException
		{
			int result = -2;
			try
				{
					Country country = new Country();
					country.setName(name);
					country.setTld(tld);
					country.setCountryID(id);

					DBConnection.startTransaction();
					IFCountry dbCountry = new DBCountry();
					result = dbCountry.updateCountry(country);
					DBConnection.commitTransaction();

				} // end of try
			catch(Exception e)
				{
					System.out.println("Could not update country, error : " + e); 
					DBConnection.rollbackTransaction();
				}

			return result;
		}
	public int createCountry(String name, String tld) throws SQLException
		{
			int result = -2;
			try
				{
					Country country = new Country();
					country.setName(name);
					country.setTld(tld);

					DBConnection.startTransaction();
					IFCountry dbCountry = new DBCountry();
					result = dbCountry.createCountry(country);
					DBConnection.commitTransaction();

				} // end of try
			catch(Exception e)
				{
					System.out.println("Could not insert a new country, error : " + e); 
					DBConnection.rollbackTransaction();
				}

			return result;
		}

}
